<template>
  <el-container class="container">
    <el-aside width="260px">
      <div class="side">
        <h2>复合查询</h2>
        <h3>选择图层</h3>
        <el-cascader
          class="el-select-100"
          expand-trigger="hover"
          :options="selectLayerList"
          size="small"
          v-model="selectedLayer"
          :props="cascaderProps"
          @change="layerChange"
        >
        </el-cascader>
        <h3>查询区域</h3>
        <el-button
          @click="draw"
          type="info"
          size="small"
        >{{ drawState ?"取消绘制":"绘制"}}</el-button>
        <h3>字段过滤</h3>
        <condition-input
          v-for="(item,index) in conditionInput"
          :key="item.id"
          v-bind:fields="queryFields"
          v-bind:index="index"
          v-bind:length="conditionInput.length"
          v-on:deleteCondition="deleteCondition"
          @uploadData="uploadData"
        ></condition-input>
        <el-button
          type="info"
          size="mini"
          icon="el-icon-plus"
          @click="addInput"
          v-if="conditionInput.length<6"
        ></el-button>
        <div class="query-btn">
          <el-button
            @click="search"
            type="info"
          >查询</el-button>
        </div>
      </div>
    </el-aside>
    <el-container>
      <el-main class="main">
        <s-map></s-map>
        <s-table
          ref="stable"
          v-if="tableShow"
          v-bind:queryFields="queryFields"
          v-bind:list="queryList"
          v-on:changeMap="changeMapPadding"
          @closeTable="closeTable"
        ></s-table>
      </el-main>
    </el-container>
  </el-container>

</template>
<style rel="stylesheet/scss" lang="scss" scoped>
@import url("http://www.dzmap.cn/webapps/other/arcgis/arcgis_js_api/library/4.7/esri/css/main.css");
.container {
  button {
    background-color: #4d6390;
  }


  .side {
    border-right: #a1a1a1 solid 1px;
    background-color: white;
    padding: 0 10px;
    height: 100%;
    position: relative;
    display: flex;
    overflow: hidden;
    box-sizing: border-box;
    flex-direction: column;
    .el-select-100 {
      width: 100%;
    }
    h3,
    h2 {
      padding: 0 0 0 15px;
      margin: 0;
      line-height: 40px;
      font-size: 14px;
      position: relative;
      &:after {
        content: "";
        width: 3px;
        height: 3px;
        background-color: #000;
        position: absolute;
        top: 19px;
        left: 5px;
        z-index: 10001;
      }
    }
    h2 {
      padding: 0;
      font-size: 16px;
      &:after {
        display: none;
      }
      &:before {
        content: "";
        width: 100%;
        height: 1px;
        background-image: linear-gradient(
          to right,
          #fff,
          #ccc,
          #ccc,
          #ccc,
          #ccc,
          #ccc,
          #fff
        );
        position: absolute;
        bottom: 0;
        left: 0;
        z-index: 3;
      }
    }
    .query-btn {
      align-self: center;
      position: absolute;
      bottom: 20px;
    }
  }
}

</style>
<script>
import { mapGetters } from 'vuex'
import { count } from '@/api/visits'
import { loadModules } from 'esri-loader';
import conditionInput from './components/ConditionInput'
import sTable from "./components/Table"
import sMap from "./components/Map"

/**
 * 记录访问，只有页面刷新或者第一次加载才会记录
 */
count().then(res => { });

export default {
  name: "MapView",
  data () {
    return {
      view: {},
      map: {},
      skViewModel: {},
      drawLayer: {},
      selectLayerList: [{}],
      selectedLayer: [],
      conditionInput: [],
      cascaderProps: {
        'label': 'label',
        'value': 'url'
      },
      tableShow: false,
      queryFields: [],
      queryList: [],
      mapPadding: '0px',
      drawState: false,
      nodes:[]
    }
  },
  components: {
    conditionInput,
    sTable,
    sMap
  },
  computed: {
    ...mapGetters(["roles"])
  },
  methods: {
    setUpClickHandler () {
      let view = this.view;
      let sketchViewModel = this.skViewModel;
      let tempGraphicsLayer = this.drawLayer;
      view.on("click", function (evt) {
        view.hitTest(evt).then(function (response) {
          var results = response.results;
          // Found a valid graphic
          if (results.length && results[results.length - 1].graphic) {
            // Check if we're already editing a graphic
            if (!updateGraphic) {
              // Save a reference to the graphic we intend to update
              updateGraphic = results[results.length - 1].graphic;
              // Remove the graphic from the GraphicsLayer
              // Sketch will handle displaying the graphic while being updated
              drawLayer.remove(updateGraphic);
              sketchViewModel.update(updateGraphic.geometry);
            }
          }
        });
      });
    },
    clearDraw () {
      this.drawLayer.removeAll()
    },
    draw () {
      this.map.reorder(this.drawLayer, 99)
      this.drawLayer.removeAll()
      if (this.drawState) {
        this.skViewModel.complete()
      } else {
        this.skViewModel.create('polygon')
      }

      
    },
    addInput () {
      let end = this.conditionInput[this.conditionInput.length - 1]
      if (end) {
        this.conditionInput.push({ id: end.id + 1, value: '' })
      } else {
        this.conditionInput.push({ id: 1, value: '' })
      }
    },
    search () {
      let _this = this
      if (_this.selectedLayer.length <= 0) {
        this.$message.error('请选择图层')
      }
      let geometry = null
      if (this.drawLayer.graphics.items[0]) {
        geometry = this.drawLayer.graphics.items[0].geometry
      }
      let url = this.selectedLayer[this.selectedLayer.length - 1] + '/0'
      let sql = ""
      loadModules(['esri/tasks/support/Query', "esri/tasks/QueryTask"], { css: false, url: "http://www.dzmap.cn/webapps/other/arcgis/arcgis_js_api/library/4.7/init.js" }).then(([Query, QueryTask]) => {
        this.conditionInput.map(v => {
          sql += v.value
        })
        let query = new Query({
          geometry: geometry,
          where: sql,
          outFields: ["*"],
          spatialRelationship: "intersects"
        })
        query.returnGeometry = false
        let qt = new QueryTask({
          url: url  // URL of a feature layer representing U.S. cities
        })

        qt.execute(query).then(function (result) {
          _this.queryList = result.features
          _this.queryFields = result.fields
          _this.tableShow = false
          _this.$nextTick(() => {
            _this.tableShow = true;
          });
        }).otherwise(err => {
          this.$message.error(err.message)
        })
      })
    },
    layerChange (value) {
      let url = value[value.length - 1] + '/0'
      let _this = this
      loadModules(['esri/tasks/support/Query', "esri/tasks/QueryTask"], { css: false, url: "http://www.dzmap.cn/webapps/other/arcgis/arcgis_js_api/library/4.7/init.js" }).then(([Query, QueryTask]) => {
        let query = new Query({
          where: "FID<0",
          outFields: ["*"],
        })
        query.returnGeometry = false
        let qt = new QueryTask({
          url: url  // URL of a feature layer representing U.S. cities
        })
        qt.execute(query).then(function (result) {
          _this.queryFields = result.fields
        })
      })
    },
    changeMapPadding (height) {
      this.mapPadding = height + "px";
    },
    deleteCondition (index) {
      let conditionInput = this.conditionInput
      this.conditionInput.splice(index, 1)
    },
    uploadData (data) {
      let index = data.index
      let value = data.data
      let sql = ""
      Object.keys(value).map(key => {
        sql += value[key] + " "
      })
      this.conditionInput[index].value = sql
    },
    closeTable(){
      this.tableShow = false
    }
  },
  beforeDestroy () {
    if (this.view) {
      this.view.container = null;
    }
  },
};
</script>

